package com.car.carcontrol.utils;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 *
 * 各种类型转换函数整理
 *
 * @author Damin
 */
public class TransformUtils {

	public  static  String comingdata = "";
	/**
	 * 16进制数字字符集
	 //	 */
//	Context parentContext;
//	SharedPreferences userInfo = parentContext.getSharedPreferences("user_info",
//			MODE_PRIVATE);
//
//	//SharedPreferences sp = getSharedPreferences("testSP", MODE_PRIVATE);
//        userInfo.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
//		@Override
//		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
//			Log.i("spTest","sp changed, key is "+ s);
//		}
//	});



	public  static  String[] feedDian = new String[]{"5AA50883173001001F74E3", "5AA50883183001001FFCE3", "5aa50782000300016dde", "5AA50883113001001FF823", "5AA50883123001001FBBE3", "5aa50782000300016dde", "5aa50782000300016dde", "5aa50782000300016dde","5aa50782000300016dde", "5aa50782000300016dde","5aa50782000300016dde", "5aa50782000300016dde","5aa50782000300016dde", "5aa50782000300016dde"};

	public static String[] sendCmd = new String[]{"5AA50883172001001F7023",
			"5AA50883182001001F7023",
			"5AA50883D1E001000085FA",
			"5AA50883112001001FF823",
			"5AA50883122001001FBC23",
			"5AA508830106010001B2A0",
			"5AA508830107010001B35C",
			"5AA508830108010001B048",
			"5AA508830201010002B7D5",
			"5AA508830202010002B791",
			"5AA508830203010002B66D",
			"5AA508830204010002B719",
			"5AA508830205010002B6E5",
			"5AA508830206010002B6A1" };
	public static String[] feedCode = new String[] {"0001","0002","0003","0004",
			"0005","0006","0007","0008",
			"0015","0016","0017","0018",
			"0019","001A"};

	private ArrayList<byte[]> FrameSpliter(byte[] data)
	{
		//本函数功能在于分割接收到的多个帧。
		//通讯协议的不完善导致TCP“捎带发送”情况下，接收方无法区分多个帧。
		//本函数用于解决这个问题，根据帧头区分帧。
		/*
		 * 输入为一个连接在一起的byte[]数组
		 *
		 * 输出为若干个独立的帧文件
		 *
		 * */
		ArrayList<byte[]> retArr=new ArrayList<byte[]>();
		int nSearchStartIndex=1;
		while (nSearchStartIndex < data.length)
		{
			int nNextPossibleFrame = ByteArrSearch(data, nSearchStartIndex, data.length-1, (byte)-21);
			if(nNextPossibleFrame < 0 || data[nNextPossibleFrame+1] != (byte)-112)
			{
				//not found
				retArr.add(Arrays.copyOfRange(data, nSearchStartIndex-1, data.length));
				break;
			}
			else
			{
				//说明确实存在下一帧
				retArr.add(Arrays.copyOfRange(data, nSearchStartIndex - 1, nNextPossibleFrame));
				nSearchStartIndex = nNextPossibleFrame + 1;
			}
		}
		return retArr;
	}

	public static boolean isAvail(String[] src,String sth)
	{
		return  IsInArray(src,sth);
	}

	public static String dectostr(int from) {
		String hexStr = "";

		if(from<100) {
			//hexStr = String.format("%02x", decAbs);
			String retStr = "";
			//Long tmp = Long.valueOf(from,16);
			//int tmpx = Integer.parseInt(from,16);
			Long tmp = Long.parseLong(from +"") ;

			//retStr = String.format("%02x",tmp);
			 retStr = Long.toHexString(tmp);
			if (retStr.length() == 1)
			{
				retStr = "0" + retStr;
			}
            hexStr = retStr;

		}


		return hexStr;
	}

	public static boolean IsInArray(String[] src,String sth)
	{
		boolean pos= false;
		int start = 0;
		int end = src.length - 1;
		//if(start < src.length && end <src.length && start>0 && end >0)
		//{

		for(int i=start;i<=end;i++)
		{
			if(src[i].equals(sth))
			{
				pos=true;
				break;
			}
		}
		//}
		return pos;
	}
	private int ByteArrSearch(byte[] data, int start, int end, byte key)
	{
		//本函数用于在一个byte[]中搜索指定byte的第一次出现。返回第一次出现的位置
		int pos= -1;
		if(start < data.length && end <data.length && start>0 && end >0)
		{

			for(int i=start;i<=end;i++)
			{
				if(data[i]==key)
				{
					pos=i;
					break;
				}
			}
		}
		return pos;
	}





	private static String hexString = "0123456789ABCDEF";

	/**
	 * 将字符串编码成16进制数字,适用于所有字符（包括中文）
	 *
	 * @param str
	 * @return String
	 */
	public static String encode(String str) {
		// 根据默认编码获取字节数组
		byte[] bytes = null;
		try {
			bytes = str.getBytes("GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	/**
	 * 将16进制数字解码成字符串,适用于所有字符（包括中文）
	 *
	 * @param bytes
	 * @return String
	 */
	public static String decode(String bytes) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(
				bytes.length() / 2);
		// 将每2位16进制整数组装成一个字节
		for (int i = 0; i < bytes.length(); i += 2)
			baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
					.indexOf(bytes.charAt(i + 1))));

		return new String(baos.toByteArray(), "GBK");

	}

	/**
	 * 把字节数组转换成16进制字符串
	 *
	 * @param bArray
	 * @return
	 */
	public static final String bytesToHexString(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)
				sb.append(0);
			sb.append(sTemp.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 把字节数组转换成16进制字符串
	 *
	 * @param src
	 * @param length
	 * @return String
	 */
	public static String bytesToHexString(byte[] src, int length) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || length <= 0) {
			return null;
		}
		for (int i = 0; i < length; i++) {
			int v = src[i] & 0xFF;
			String hv = " 0x" + Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 把16进制字符串转换成字节数组
	 *
	 * @param hex
	 * @return
	 */

	public static   String getExchangeCmdx(String cmd)

	{
		String retStr = cmd.substring(0,2) + "3";
		if(cmd.substring(2,3).equals("2"))
		{
			retStr  = retStr + cmd.substring(3,6);
		}
		else {
			retStr = cmd;
		}
		return  retStr;
	}

	public  boolean checkAvailable(String data)

	{
		boolean result = false;


		return  result;
	}

	public static   String heCheng(String cmd)

	{
		String retStr = "";
//		for(int k = 0; k < 8; k++) {
//			if (cmd.equals(TransformUtils.sendCmd[k])) {
//				retStr = feedDian[k];
//			}
//		}

		return  retStr;
	}

	public static   int findPosition(String[] cmd,String comp)

	{
		int retStr = -1;
		for(int k = 0; k < cmd.length; k++) {
			if (cmd[k].equals(comp)) {
				retStr = k;
			}
		}
//		if(cmd.equals(TransformUtils.sendCmd[1]))
//		{
//			retStr  = feedDian[1];
//		}
		return  retStr;
	}


	public static   String getAddress(String from,int count)

	{
//		String retStr = "";
//		Long tmp = Long.valueOf(from,16);
//		int tmpx = Integer.parseInt(from,16);
//		tmp = tmp + count;
//
//		//	retStr = String.format("%04X",tmp);
//		retStr = Long.toHexString(tmp);
//		// retStr = "00" + retStr;
//		//retStr =  retStr;
//		return  retStr;
		String retStr = "";
		Long tmp = Long.valueOf(from,16);
		int tmpx = Integer.parseInt(from,16);
		tmp = tmp + count;

		//retStr = String.format("%02x",tmp);
		String retStrx = Long.toHexString(tmp);
		if (retStrx.length() == 3)
		{
			retStrx = "0" + retStrx;
		}
		// retStr = "00" + retStr;
		//retStr =  retStr;
		return  retStrx;
	}

	public static   String getupCmd(String[] ups,String[] downs,String cmd)

	{
		String retStr = "";
		int position = findPosition(downs, cmd);
		retStr = ups[position];
		return  retStr;
	}

	public static   String getExchangeCmd(String cmd)

	{
		String   cmdheader = "5AA50883";
		String   feedheader = "5AA5";
//		String  allCmdx = cmdheader;
//
//		allCmdx =  allCmdx.concat(CRC16.expandStr(lcmd1Array[cbtn]));
//		allCmd = CRC16.crc16x(allCmdx);
		String retStr = "";
		String tmp = cmd.substring(10,11);
		if(tmp.equals("2")) {
			retStr = cmd.substring(8,10) + "3" + cmd.substring(11,16);
		}


		String  allCmdx = cmdheader;


		allCmdx = allCmdx.concat(CRC16.expandStr(retStr ));
		StringBuffer allCmd = CRC16.crc16x(allCmdx);

		final String cmdw = allCmd.substring(0, 22);

		return  cmdw;
	}
	public static   String getExchangeCmdy(String cmd)

	{
		String retStr = "";
		for(int k = 0; k < 8; k++) {
			if (cmd.equals(TransformUtils.sendCmd[k])) {
				retStr = feedDian[k];
			}
		}
//		if(cmd.equals(TransformUtils.sendCmd[1]))
//		{
//			retStr  = feedDian[1];
//		}
		return  retStr;
	}

	public static byte[] hexStringToBytes(String hex) {
		while (hex.length() < 2)
			return null;
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (charToByte(achar[pos]) << 4 | charToByte(achar[pos + 1]));
		}
		return result;
	}

	public static byte charToByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}

	/**
	 * int to byte
	 *
	 * @param 0 <= input <= 255
	 * @return
	 */
	public static byte intToByte(int input) {
		byte output1;
		output1 = (byte) (input & 0xff);
		return output1;
	}

	/**
	 * byte to int
	 *
	 * @param b
	 * @return
	 */
	public static int byteToInt(byte b) {
		return b < 0 ? b & 0x7F + 128 : b;
	}
}
